<template>
  <div>
     <a-card title="添加健康数据">
      <a-form :model="form" layout="inline" @submit.prevent="handleAdd">
        <a-form-item label="性别">
          <a-select v-model:value="form.gender" style="width: 80px">
            <a-select-option :value="0">男</a-select-option>
            <a-select-option :value="1">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="年龄">
          <a-input-number v-model:value="form.age" :min="1" :max="120" style="width: 80px" />
        </a-form-item>
        <a-form-item label="身高(cm)">
          <a-input-number v-model:value="form.height" :min="50" :max="250" style="width: 100px" />
        </a-form-item>
        <a-form-item label="体重(kg)">
          <a-input-number v-model:value="form.weight" :min="10" :max="300" style="width: 100px" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleAdd" :loading="addLoading">添加</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-card title="健康数据记录" style="margin-bottom: 24px;">
      <a-table 
        :columns="columns" 
        :data-source="data" 
        :pagination="pagination" 
        row-key="id" 
        :loading="loading"
        @row-click="onRowClick"
        :customRow="row => ({ onClick: () => onRowClick(row) })"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'gender'">
            {{ record.gender === 1 ? '女' : '男' }}
          </template>
          <template v-else-if="column.dataIndex === 'bodyFatResult'">
            <div v-if="record.bodyFatResult">
              体脂率: {{ record.bodyFatResult.bodyFatPercentage }}<br>
              BMI: {{ record.bodyFatResult.bmi }}<br>
              分类: {{ record.bodyFatResult.bodyFatCategory }}
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" danger size="small" @click.stop="handleDelete(record.id)">删除</a-button>
          </template>
          <template v-else>
            {{ record[column.dataIndex] }}
          </template>
        </template>
      </a-table>
      <a-modal v-model:open="recommendVisible" title="健  康饮食推荐" :footer="null" width="700px" @cancel="recommendVisible=false">
        <div v-if="recommendLoading" style="text-align:center;padding:40px 0;">
          <a-spin />
        </div>
        <div v-else-if="recommendData" class="recommend-html-content">
          <a-card title="健康信息" style="margin-bottom: 16px">
            <div v-html="renderMarkdown(getInfoMarkdown(recommendData))" />
          </a-card>
          <a-card title="饮食推荐">
            <div v-if="recommendData.referrals">
              <div v-html="renderMarkdown(recommendData.referrals)" />
            </div>
            <div v-else>
              <div v-html="renderMarkdown('暂无推荐')" />
            </div>
          </a-card>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { message } from 'ant-design-vue'
import { marked } from 'marked'

const columns = [
  { title: '性别', dataIndex: 'gender', key: 'gender' },
  { title: '年龄', dataIndex: 'age', key: 'age' },
  { title: '身高(cm)', dataIndex: 'height', key: 'height' },
  { title: '体重(kg)', dataIndex: 'weight', key: 'weight' },
  { title: '体脂分析', dataIndex: 'bodyFatResult', key: 'bodyFatResult' },
  { title: '操作', dataIndex: 'action', key: 'action', align: 'center' }
]

const data = ref([]) // 默认空数组
const loading = ref(false)
const pagination = ref({ current: 1, pageSize: 20, total: 0, showTotal: t => `共${t}条` })
const form = ref({ gender: '', age: '', height: '', weight: '' })
const addLoading = ref(false)
const recommendVisible = ref(false)
const recommendLoading = ref(false)
const recommendData = ref(null)


async function fetchData(page = 1, pageSize = 20) {
  loading.value = true
  try {
    const token = localStorage.getItem('accessToken')
    const res = await axios.get('http://192.168.0.22:7044/api/module/AISlimmingAssistant/Page', {
      params: { PageNumber: page, PageSize: pageSize },
      headers: { Authorization: `Bearer ${token}` }
    })
    if (res.data && res.data.success) {
      data.value = res.data.data || []
      pagination.value.total = res.data.total
      pagination.value.current = res.data.current
      pagination.value.pageSize = res.data.pageSize
    }
  } finally {
    loading.value = false
  }
}

async function handleAdd() {
  addLoading.value = true
  try {
    const token = localStorage.getItem('accessToken')
    const res = await axios.post('http://192.168.0.22:7044/api/module/AISlimmingAssistant', form.value, {
      headers: { Authorization: `Bearer ${token}` }
    })
    if (res.data && res.data.success) {
      message.success('添加成功')
      fetchData(pagination.value.current, pagination.value.pageSize)
    }
  } finally {
    addLoading.value = false
  }
}

async function handleDelete(id) {
  if (!id) return
  loading.value = true
  try {
    const token = localStorage.getItem('accessToken')
    const res = await axios.delete('http://192.168.0.22:7044/api/module/AISlimmingAssistant', {
      params: { id },
      headers: { Authorization: `Bearer ${token}` }
    })
    if (res.data && res.data.success) {
      message.success('删除成功')
      fetchData(pagination.value.current, pagination.value.pageSize)
    } else {
      message.error(res.data?.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

async function onRowClick(record) {
  if (!record?.id) return
  if (record.referrals) {
    recommendData.value = record
    recommendVisible.value = true
    recommendLoading.value = false
    return
  }
  recommendVisible.value = true
  recommendLoading.value = true
  recommendData.value = null
  try {
    const token = localStorage.getItem('accessToken')
    const res = await axios.post(`http://192.168.0.22:7044/api/module/AISlimmingAssistant/${record.id}`,
      {},
      { headers: { Authorization: `Bearer ${token}` } }
    )
    if (res.data && res.data.success) {
      recommendData.value = res.data.data
    } else {
      recommendData.value = { referrals: res.data?.message || '获取推荐失败' }
    }
  } finally {
    recommendLoading.value = false
  }
}

function getInfoMarkdown(data) {
  if (!data) return ''
  let md = `性别：${data.gender === 1 ? '女' : '男'}     年龄：${data.age}    身高：${data.height}cm    体重：${data.weight}kg\n`
  if (data.bodyFatResult) {
    md += `\n体脂率：${data.bodyFatResult.bodyFatPercentage}\nBMI：${data.bodyFatResult.bmi}\n分类：${data.bodyFatResult.bodyFatCategory}\n`
  }
  return md
}


function renderMarkdown(md) {
  return marked.parse(md || '')
}



onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.recommend-html-content {
  font-size: 15px;
  line-height: 1.8;
  color: #333;
  background: #fafbfc;
  border-radius: 8px;
  padding: 18px 22px 18px 22px;
  margin: 0 0 0 0;
  box-shadow: 0 2px 8px #00000014;
  max-height: 60vh;
  overflow-y: auto;
}
.recommend-html-content h2, .recommend-html-content h3, .recommend-html-content h4 {
  margin: 18px 0 8px 0;
  font-weight: bold;
  color: #2b6cb0;
}
.recommend-html-content ul {
  margin: 8px 0 8px 20px;
  padding-left: 18px;
}
.recommend-html-content li {
  margin-bottom: 4px;
}
.recommend-html-content b {
  color: #1a202c;
}
.recommend-html-content hr {
  border: none;
  border-top: 1px solid #e2e8f0;
  margin: 18px 0;
}
</style>
